<template>
	<view class="grid g4 ptb0">
		<view class="plr5 father" v-for="( item , index) in list" :key="index" v-if="index < countSync">
			<view class="square  rds3">
				<image class="bd2" @tap="preview(item)" :src="item" mode="aspectFill"></image>
				<view class="abs top right" style="width: auto;height: auto;" @tap="deleteImage(index)" v-if="!disabled">
					<view class=" blackBg plr10 rdsTr4 rdsBl4 op5 fz12 z4">x</view>
				</view>
			</view>
		</view>
		<view class="plr5" @tap="toUploadImage" v-if="!disabled && list.length < countSync">
			<view class="square bd2 rds3">
				<view class="flex center">
					<view class="grey fz20 sIcon-photoFill"></view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {Qiniu} from "../../common/upload.js" ;
	export default {
		name: 'uploadPic',
		data() {
			return {
				list : [] ,
				qiniu : new Qiniu() 
			};
		},
		props: {
			count: {
				type: [Number,String],
				default: 9
			},
			value : {
				default : ""
			},
			disabled : {
				default : false 
			}
		},
		
		computed:{
			countSync:function(e){
				return Number(this.count);
			},
		},
		
		watch:{
			value : function(){
				if (!this.value) {
					return ;
				}
				this.list = typeof this.value == 'object' ? this.value : this.value.split(",") ;
			},
		},
		
		methods: {
			toUploadImage:function(key){
				var sourceTypes = ["album", "camera"];
				uni.showActionSheet({
					itemList:["从相册选择","从相机拍照"],
					success : res => {
						uni.chooseImage({
							sourceType:[sourceTypes[res.tapIndex]],
							count: this.countSync ,
							success: res =>{
								uni.showNavigationBarLoading();
								var arr = res.tempFilePaths ;
								var nowLength = this.list.length ;
								for (var i = 0; i < arr.length; i++) {
									var path = arr[i] ;
									this.qiniu.upload(path , res =>{
										if (this.list.length <= this.countSync) {
											this.list.push(res);
											this.change();
										}
										if (this.list.length - nowLength == arr.length) {
											uni.hideNavigationBarLoading();
										}
									});
								}
							}
						});
					}
				});
			},
			
			preview:function(e){
				uni.previewImage({
					urls:this.list ,
					current: e 
				});
			},
			
			deleteImage:function(index){
				this.list.splice(index,1);
				this.change();
			},
			
			change:function(e){
				this.$emit('change' , { list : this.list , value : this.list.join(",") });
			},
		}
	}
</script>

<style>

</style>
